.export _slowkey
.export _scantable
.export _joystick
.export _joy_horizontal
.export _joy_vertical
.export _joy_fire

pa = $dc00
pb = $dc01
ddra = $dc02
ddrb = $dc03
mask = $03
.data
_scantable:
	.byte 0, 0, 0, 0, 0, 0, 0, 0

.code
_slowkey:
	; sei
	ldx #0
	lda #$fe
	sta mask
slowkey_nextrow:
	lda mask
	sta pa
slowkey_back:
	lda pb
	cmp pb
	bne slowkey_back
	eor #$ff
	sta _scantable, x
	sec
	rol mask
	inx
	cpx #8
	bcc slowkey_nextrow
	; cli
	rts

.data
_joy_horizontal: .byte 0
_joy_vertical:	 .byte 0
_joy_fire:		 .byte 0

.code
_joystick:
djrr:   lda $dc00     ; get input from port 2 only
djrrb:  ldy #0        ; this routine reads and decodes the
        ldx #0        ; joystick/firebutton input data in
        lsr           ; the accumulator. this least significant
        bcs djr0      ; 5 bits contain the switch closure
        dey           ; information. if a switch is closed then it
djr0:   lsr           ; produces a zero bit. if a switch is open then
        bcs djr1      ; it produces a one bit. The joystick dir-
        iny           ; ections are right, left, forward, backward
djr1:   lsr           ; bit3=right, bit2=left, bit1=backward,
        bcs djr2      ; bit0=forward and bit4=fire button.
        dex           ; at rts time dx and dy contain 2's compliment
djr2:   lsr           ; direction numbers i.e. $ff=-1, $00=0, $01=1.
        bcs djr3      ; dx=1 (move right), dx=-1 (move left),
        inx           ; dx=0 (no x change). dy=-1 (move up screen),
djr3:   lsr           ; dy=0 (move down screen), dy=0 (no y change).
        stx _joy_horizontal        ; the forward joystick position corresponds
        sty _joy_vertical        ; to move up the screen and the backward
        lda #$01
        bcc joy_done
        lda #$00
joy_done:
        sta _joy_fire
        rts           ; position to move down screen.
                      ;
                      ; at rts time the carry flag contains the fire
                      ; button state. if c=1 then button not pressed.
                      ; if c=0 then pressed.